import os
import shutil
import zipfile
import re

# 配置信息
DOCS_DIR = os.path.join(os.getcwd(), 'docs')
OUTPUT_DIR = os.path.join(os.getcwd(), 'output')

def clear_output_dir():
    """清空output目录下的所有内容"""
    if os.path.exists(OUTPUT_DIR):
        for item in os.listdir(OUTPUT_DIR):
            item_path = os.path.join(OUTPUT_DIR, item)
            try:
                if os.path.isfile(item_path):
                    os.remove(item_path)
                elif os.path.isdir(item_path):
                    shutil.rmtree(item_path)
            except PermissionError:
                print(f"警告: 无法删除 {item_path}，可能正在被其他程序使用")
            except Exception as e:
                print(f"警告: 删除 {item_path} 时出错: {e}")
    else:
        os.makedirs(OUTPUT_DIR)
    print("已清空output目录")

def process_student_docs(student_id, student_name):
    """处理指定学生的文档"""
    # 创建学生文件夹
    student_folder_name = f"{student_id}-{student_name}"
    student_folder_path = os.path.join(OUTPUT_DIR, student_folder_name)
    if not os.path.exists(student_folder_path):
        os.makedirs(student_folder_path)
    
    print(f"正在处理学生: {student_id}-{student_name}")
    
    # 获取论文题目
    thesis_title = get_thesis_title(student_id, student_name)
    if not thesis_title:
        print(f"警告: 无法确定学生 {student_id}-{student_name} 的论文题目")
        # 使用默认论文题目
        thesis_title = "未知论文题目"
    
    print(f"论文题目: {thesis_title}")
    
    # 处理各类文档
    process_task_book(student_id, student_name, student_folder_path)
    process_proposal(student_id, student_name, student_folder_path)
    process_guidance_record(student_id, student_name, student_folder_path)
    process_supervisor_review(student_id, student_name, student_folder_path)
    process_cross_review(student_id, student_name, student_folder_path)
    process_defense_record_1(student_id, student_name, student_folder_path)
    process_defense_record_2(student_id, student_name, student_folder_path)
    process_final_grade(student_id, student_name, student_folder_path)
    process_thesis(student_id, student_name, thesis_title, student_folder_path)
    process_plagiarism_report(student_id, student_name, thesis_title, student_folder_path)
    process_aigc_report(student_id, student_name, thesis_title, student_folder_path)
    
    # 压缩文件夹
    try:
        zip_student_folder(student_id, student_name)
    except Exception as e:
        print(f"压缩文件夹时出错: {e}")
    
    print(f"学生 {student_id}-{student_name} 的文档处理完成")

def get_thesis_title(student_id, student_name):
    """获取学生的论文题目"""
    # 在docs目录下查找包含学生学号和姓名的论文文件
    for filename in os.listdir(DOCS_DIR):
        # 检查最终稿文件
        if "-最终稿.docx" in filename and student_id in filename and student_name in filename:
            print(f"找到论文文件: {filename}")
            # 尝试提取论文题目
            try:
                # 尝试多种模式匹配论文题目
                # 模式1: 学号-姓名-论文题目-最终稿.docx
                match = re.search(f"{student_id}-{student_name}-(.*)-最终稿\.docx", filename)
                if match:
                    return match.group(1)
                
                # 模式2: 专业-班级-姓名-学号-论文题目-最终稿.docx
                match = re.search(f".*-{student_name}-{student_id}-(.*)-最终稿\.docx", filename)
                if match:
                    return match.group(1)
                
                # 如果上述模式都不匹配，尝试从文件名中提取
                parts = filename.split('-')
                # 找到学号和最终稿的位置
                student_id_index = -1
                final_draft_index = -1
                for i, part in enumerate(parts):
                    if student_id in part:
                        student_id_index = i
                    if "最终稿" in part:
                        final_draft_index = i
                
                if student_id_index != -1 and final_draft_index != -1 and final_draft_index > student_id_index:
                    # 提取学号和最终稿之间的部分作为论文题目
                    title_parts = parts[student_id_index+1:final_draft_index]
                    if title_parts:
                        return '-'.join(title_parts)
            except Exception as e:
                print(f"从文件名 {filename} 提取论文题目时出错: {e}")
        
        # 检查检测报告文件
        if "检测报告" in filename and student_id in filename and student_name in filename:
            print(f"找到检测报告文件: {filename}")
            try:
                # 从检测报告文件名中提取论文题目
                match = re.search(f".*{student_id}.*{student_name}-(.*)\.zip", filename)
                if match:
                    return match.group(1)
            except Exception as e:
                print(f"从文件名 {filename} 提取论文题目时出错: {e}")
    
    # 如果找不到论文题目，返回None
    return None

def find_file_by_pattern(pattern):
    """在docs目录下查找匹配模式的文件"""
    for filename in os.listdir(DOCS_DIR):
        if re.search(pattern, filename):
            return os.path.join(DOCS_DIR, filename)
    return None

def process_task_book(student_id, student_name, student_folder_path):
    """处理任务书"""
    source_file = find_file_by_pattern(f"{student_id}-{student_name}-任务书\.docx")
    if source_file:
        target_file = os.path.join(student_folder_path, f"1.{student_id}-{student_name}-本科毕业设计（论文）任务书.docx")
        shutil.copy2(source_file, target_file)
        print(f"已复制任务书: {os.path.basename(target_file)}")
    else:
        print(f"警告: 未找到学生 {student_id}-{student_name} 的任务书")

def process_proposal(student_id, student_name, student_folder_path):
    """处理开题报告"""
    source_file = find_file_by_pattern(f"{student_id}-{student_name}-开题报告\.docx")
    if source_file:
        target_file = os.path.join(student_folder_path, f"2.{student_id}-{student_name}-本科毕业设计（论文）开题报告.docx")
        shutil.copy2(source_file, target_file)
        print(f"已复制开题报告: {os.path.basename(target_file)}")
    else:
        print(f"警告: 未找到学生 {student_id}-{student_name} 的开题报告")

def process_guidance_record(student_id, student_name, student_folder_path):
    """处理指导记录"""
    source_file = find_file_by_pattern(f"指导记录-{student_id}-{student_name}\.docx")
    if not source_file:
        # 尝试其他可能的格式
        source_file = find_file_by_pattern(f"指导记录.*{student_id}.*{student_name}\.docx")
    
    if source_file:
        target_file = os.path.join(student_folder_path, f"3.{student_id}-{student_name}-本科毕业设计（论文）指导记录表.docx")
        shutil.copy2(source_file, target_file)
        print(f"已复制指导记录: {os.path.basename(target_file)}")
    else:
        print(f"警告: 未找到学生 {student_id}-{student_name} 的指导记录")

def process_supervisor_review(student_id, student_name, student_folder_path):
    """处理指导教师评阅表"""
    source_file = find_file_by_pattern(f"指导教师评阅表.*{student_id}.*{student_name}\.docx")
    if source_file:
        target_file = os.path.join(student_folder_path, f"4-1.{student_id}-{student_name}-本科毕业设计（论文）评阅表（指导教师评阅表）.docx")
        shutil.copy2(source_file, target_file)
        print(f"已复制指导教师评阅表: {os.path.basename(target_file)}")
    else:
        print(f"警告: 未找到学生 {student_id}-{student_name} 的指导教师评阅表")

def process_cross_review(student_id, student_name, student_folder_path):
    """处理交叉评阅表"""
    source_file = find_file_by_pattern(f"交叉评阅表-{student_id}-{student_name}\.docx")
    if not source_file:
        # 尝试其他可能的格式
        source_file = find_file_by_pattern(f"交叉评阅表.*{student_id}.*{student_name}\.docx")
    
    if source_file:
        target_file = os.path.join(student_folder_path, f"4-2.{student_id}-{student_name}-本科毕业设计（论文）评阅表（评阅教师评阅表）.docx")
        shutil.copy2(source_file, target_file)
        print(f"已复制交叉评阅表: {os.path.basename(target_file)}")
    else:
        print(f"警告: 未找到学生 {student_id}-{student_name} 的交叉评阅表")

def process_defense_record_1(student_id, student_name, student_folder_path):
    """处理一辩答辩记录及成绩表"""
    source_file = find_file_by_pattern(f"（一辩）答辩记录及成绩表-{student_id}-{student_name}\.docx")
    if not source_file:
        # 尝试其他可能的格式
        source_file = find_file_by_pattern(f"（一辩）答辩记录.*{student_id}.*{student_name}\.docx")
    
    if source_file:
        target_file = os.path.join(student_folder_path, f"5-1.{student_id}-{student_name}-本科毕业设计（论文）答辩记录及成绩表（1辩）.docx")
        shutil.copy2(source_file, target_file)
        print(f"已复制一辩答辩记录: {os.path.basename(target_file)}")
    else:
        print(f"警告: 未找到学生 {student_id}-{student_name} 的一辩答辩记录")

def process_defense_record_2(student_id, student_name, student_folder_path):
    """处理二辩答辩记录及成绩表"""
    source_file = find_file_by_pattern(f"（二辩）答辩记录及成绩表-{student_id}-{student_name}\.docx")
    if not source_file:
        # 尝试其他可能的格式
        source_file = find_file_by_pattern(f"（二辩）答辩记录.*{student_id}.*{student_name}\.docx")
    
    if source_file:
        target_file = os.path.join(student_folder_path, f"5-2.{student_id}-{student_name}-本科毕业设计（论文）答辩记录及成绩表（2辩）.docx")
        shutil.copy2(source_file, target_file)
        print(f"已复制二辩答辩记录: {os.path.basename(target_file)}")
    else:
        print(f"警告: 未找到学生 {student_id}-{student_name} 的二辩答辩记录")

def process_final_grade(student_id, student_name, student_folder_path):
    """处理总评成绩"""
    source_file = find_file_by_pattern(f"总评成绩-{student_id}-{student_name}\.docx")
    if not source_file:
        # 尝试其他可能的格式
        source_file = find_file_by_pattern(f"总评成绩.*{student_id}.*{student_name}\.docx")
    
    if source_file:
        target_file = os.path.join(student_folder_path, f"6.{student_id}-{student_name}-本科毕业设计（论文）成绩评定总表.docx")
        shutil.copy2(source_file, target_file)
        print(f"已复制总评成绩: {os.path.basename(target_file)}")
    else:
        print(f"警告: 未找到学生 {student_id}-{student_name} 的总评成绩")

def process_thesis(student_id, student_name, thesis_title, student_folder_path):
    """处理论文最终稿"""
    # 查找论文文件
    source_file = None
    for filename in os.listdir(DOCS_DIR):
        if "-最终稿.docx" in filename and student_id in filename and student_name in filename:
            source_file = os.path.join(DOCS_DIR, filename)
            break
    
    if source_file:
        target_file = os.path.join(student_folder_path, f"7.{student_id}-{student_name}-{thesis_title}.docx")
        shutil.copy2(source_file, target_file)
        print(f"已复制论文最终稿: {os.path.basename(target_file)}")
    else:
        print(f"警告: 未找到学生 {student_id}-{student_name} 的论文最终稿")

def extract_and_copy_report(zip_file_path, report_pattern, target_file):
    """从ZIP文件中提取报告并复制到目标位置"""
    if not os.path.exists(zip_file_path):
        return False
    
    # 创建临时目录
    temp_dir = os.path.join(OUTPUT_DIR, "temp_extract")
    if os.path.exists(temp_dir):
        shutil.rmtree(temp_dir)
    os.makedirs(temp_dir)
    
    try:
        # 解压ZIP文件
        with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
            zip_ref.extractall(temp_dir)
        
        # 查找报告文件
        report_file = None
        for root, _, files in os.walk(temp_dir):
            for file in files:
                if re.search(report_pattern, file):
                    report_file = os.path.join(root, file)
                    break
            if report_file:
                break
        
        if report_file:
            # 复制报告文件到目标位置
            shutil.copy2(report_file, target_file)
            return True
    except Exception as e:
        print(f"处理ZIP文件时出错: {e}")
    finally:
        # 清理临时目录
        if os.path.exists(temp_dir):
            shutil.rmtree(temp_dir)
    
    return False

def process_plagiarism_report(student_id, student_name, thesis_title, student_folder_path):
    """处理查重报告"""
    # 查找查重报告ZIP文件
    zip_file = find_file_by_pattern(f"学生提交论文最终稿-检测报告.*{student_id}.*{student_name}.*\.zip")
    
    if zip_file:
        target_file = os.path.join(student_folder_path, f"8.{student_id}-{student_name}-查重报告：{thesis_title}.pdf")
        # 提取简洁报告
        if extract_and_copy_report(zip_file, f"{thesis_title}_简洁报告\.pdf", target_file):
            print(f"已复制查重报告: {os.path.basename(target_file)}")
        else:
            print(f"警告: 未能从ZIP文件中提取学生 {student_id}-{student_name} 的查重报告")
    else:
        print(f"警告: 未找到学生 {student_id}-{student_name} 的查重报告ZIP文件")

def process_aigc_report(student_id, student_name, thesis_title, student_folder_path):
    """处理AIGC检测报告"""
    # 查找AIGC检测报告ZIP文件
    zip_file = find_file_by_pattern(f"学生提交论文最终稿-AIGC检测报告.*{student_id}.*{student_name}.*\.zip")
    
    if zip_file:
        target_file = os.path.join(student_folder_path, f"9.{student_id}-{student_name}-AIGC检测报告：{thesis_title}.pdf")
        # 提取AIGC存档报告
        if extract_and_copy_report(zip_file, f"{thesis_title}_AIGC存档报告\.pdf", target_file):
            print(f"已复制AIGC检测报告: {os.path.basename(target_file)}")
        else:
            print(f"警告: 未能从ZIP文件中提取学生 {student_id}-{student_name} 的AIGC检测报告")
    else:
        print(f"警告: 未找到学生 {student_id}-{student_name} 的AIGC检测报告ZIP文件")

def zip_student_folder(student_id, student_name):
    """将学生文件夹压缩为ZIP文件"""
    folder_name = f"{student_id}-{student_name}"
    folder_path = os.path.join(OUTPUT_DIR, folder_name)
    zip_path = os.path.join(OUTPUT_DIR, f"{folder_name}.zip")
    
    # 如果已存在同名ZIP文件，先删除，如果无法删除则使用临时文件名
    temp_zip_path = zip_path
    if os.path.exists(zip_path):
        try:
            os.remove(zip_path)
        except PermissionError:
            print(f"无法删除已存在的ZIP文件: {zip_path}，将使用临时文件名")
            temp_zip_path = os.path.join(OUTPUT_DIR, f"{folder_name}_new.zip")
            if os.path.exists(temp_zip_path):
                try:
                    os.remove(temp_zip_path)
                except:
                    pass
    
    try:
        # 创建ZIP文件
        with zipfile.ZipFile(temp_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
            for root, _, files in os.walk(folder_path):
                for file in files:
                    file_path = os.path.join(root, file)
                    # 计算相对路径
                    rel_path = os.path.relpath(file_path, OUTPUT_DIR)
                    zipf.write(file_path, rel_path)
        
        # 如果使用了临时文件名，尝试重命名为正确的文件名
        if temp_zip_path != zip_path:
            try:
                if os.path.exists(zip_path):
                    os.remove(zip_path)
                os.rename(temp_zip_path, zip_path)
            except:
                print(f"无法重命名ZIP文件，保留为临时文件名: {os.path.basename(temp_zip_path)}")
        
        print(f"已创建ZIP文件: {os.path.basename(zip_path) if temp_zip_path == zip_path else os.path.basename(temp_zip_path)}")
    except Exception as e:
        print(f"创建ZIP文件时出错: {e}")

def main():
    try:
        # 清空output目录
        clear_output_dir()
        
        # 从docs目录中获取学生信息
        student_info = []
        
        # 首先尝试从任务书和开题报告中提取学生信息
        for filename in os.listdir(DOCS_DIR):
            # 匹配格式：学号-姓名-任务书.docx 或 学号-姓名-开题报告.docx
            match = re.match(r'(\d+)-([^-]+)-(任务书|开题报告)\.docx$', filename)
            if match:
                student_id = match.group(1)
                student_name = match.group(2)
                student_info.append((student_id, student_name))
                break  # 找到一个就足够了
        
        # 如果没有找到，尝试其他文件格式
        if not student_info:
            for filename in os.listdir(DOCS_DIR):
                # 尝试从其他文件名中提取
                match = re.search(r'(\d+)-([^-\.]+)', filename)
                if match:
                    student_id = match.group(1)
                    student_name = match.group(2)
                    student_info.append((student_id, student_name))
                    break  # 找到一个就足够了
        
        # 如果仍然没有找到，使用硬编码的学生信息（从目录结构中可以看到）
        if not student_info:
            student_info = [("209030233", "黄麒麟")]
        
        if not student_info:
            print("未找到任何学生信息")
            return
        
        print(f"找到以下学生信息:")
        for student_id, student_name in student_info:
            print(f"  - {student_id}-{student_name}")
        
        # 处理每个学生的文档
        for student_id, student_name in student_info:
            try:
                process_student_docs(student_id, student_name)
            except Exception as e:
                print(f"处理学生 {student_id}-{student_name} 的文档时出错: {e}")
    except Exception as e:
        print(f"程序执行过程中出错: {e}")

if __name__ == "__main__":
    main()